package com.solocredit.finance.ui.loan.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.view.View
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.databinding.ActMullaRepaymentBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.loan.impl.MullaLoanRepayPresenterImpl
import com.solocredit.finance.ui.loan.view.IMullaLoanRepayView
import com.solocredit.finance.utils.dialog.CouponUseDialog
import com.solocredit.finance.utils.dialog.NoticeDialog
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.utils.track.FlexiMolaTracker
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/8 14:14
 * @Annotation：还款页
 */
class MullaLoanRepayAct: MvpAct<IMullaLoanRepayView, MullaLoanRepayPresenterImpl>(),IMullaLoanRepayView {
    lateinit var binding: ActMullaRepaymentBinding
    private var pName = ""
    //是否逾期，逾期会在退出页面上报埋点
    private var isOverdue = false

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, MullaLoanRepayAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun createPresenter(): MullaLoanRepayPresenterImpl {
        return MullaLoanRepayPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaRepaymentBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
        setMullaTextTitle(getString(R.string.loan_repayment_title))

        binding.parentLayout.visibility = View.GONE
        initMullaRefreshLayout()
    }

    override fun initMullaListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("$pName Repay Page",pName,loadProductToken())
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"$pName Repay Page")
        }

        //选择抵扣券
        binding.couponLayout.setOnClickListener {
            presenter.onMullaChooseCouponAction()
        }

        //还款
        binding.repayLayout.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LOAN_REPAY,"$pName Repay Page")
            // TODO: 还款 批量埋点上报
            FlexiMolaTracker.getInstance(MyApp.app).reportImmediately(null)

            showMullaLoading(false, isCancel = true)
            presenter.loadMullaLoanPayLinkAction()
        }
    }

    override fun initMullaData() {
        showMullaLoading(isTOuchOut = false, isCancel = true)
        presenter.loadMullaLoanRepayInfoAction()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter.loadMullaLoanRepayInfoAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    override fun loadProductName(): String {
        return intent.extras?.getString(INTENT_KEY_PRODUCT).toString()
    }

    override fun loadProductToken(): String {
        return intent.extras?.getString(INTENT_KEY_TOKEN).toString()
    }

    @SuppressLint("SetTextI18n")
    override fun showMullaRepayInfo(data: JSONObject) {
        binding.parentLayout.visibility = View.VISIBLE
        binding.loanAmountLayout.visibility = View.GONE
        //单位
        val unit = data.optString("currency")
        val overdueDay = data.optString("overdueDay")

        binding.textTotalAmount.text = "${data.optString("repayAmount")} $unit"
        binding.textDueDate.text = data.optString("repayDate")
        binding.textLoanAmount.text = "${data.optString("amount")} $unit"
        binding.textInterest.text = "${data.optString("interest")} $unit"
        if (data.optDouble("serviceFee") <= 0){
            binding.serviceFeeLayout.visibility = View.GONE
        } else {
            binding.serviceFeeLayout.visibility = View.VISIBLE
            binding.textServiceFee.text = "${data.optString("serviceFee")} $unit"
        }
        binding.textDueDays.text = String.format(getString(R.string.loan_repaylist_days),overdueDay)
        binding.textDueAmount.text = "${data.optString("overdueAmount")} $unit"
        binding.textPoints.text = String.format(getString(R.string.step_contact_add_points),data.optString("score"))

        isOverdue = overdueDay.toInt() > 0
        if (isOverdue){//已逾期
            val showStatus = String.format(getString(R.string.loan_repayment_days_overdue),overdueDay)
            binding.textStatus.setTextColor(Color.parseColor("#FFFF6A6A"))
            binding.textStatus.text = showStatus

            binding.textLoanAmount.setTextColor(Color.parseColor("#FFFF5B27"))
            binding.textDueDays.setTextColor(Color.parseColor("#FFFF5B27"))
            binding.textDueDays.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
            binding.textDueAmount.setTextColor(Color.parseColor("#FFFF5B27"))
            binding.textDueAmount.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
        } else {
            val showStatus = String.format(getString(R.string.loan_repayment_days_left),data.optString("remainRepayDay"))
            binding.textStatus.setTextColor(Color.parseColor("#FFFFFFFF"))
            binding.textStatus.text = showStatus

            binding.textLoanAmount.setTextColor(Color.parseColor("#FF160807"))
            binding.textDueDays.setTextColor(Color.parseColor("#FF666666"))
            binding.textDueDays.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
            binding.textDueAmount.setTextColor(Color.parseColor("#FF666666"))
            binding.textDueAmount.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        }
        if (getMullaUserCouponCount() == 0){
            binding.textCouponDiscount.text = getString(R.string.coupon_list_none)
            binding.couponLayout.isEnabled = false
        } else {
            //加载优惠券
            presenter.loadMullaUserCouponListAction()
        }

        //还款公告信息
        showMullaLoanNoticeDialog()
    }

    /**
     * 设置默认使用优惠券信息
     */
    @SuppressLint("SetTextI18n")
    override fun showMullaDufauleUseCouponInfo(data: JSONObject?) {
        presenter.repayInfo?.let {
            //单位
            val unit = it.optString("currency")
            //待还金额
            val repayAmount = it.optDouble("repayAmount")
            //不使用优惠券
            if(data == null){
                binding.textCouponDiscount.text = "－0 $unit"
                binding.couponLayout.isEnabled = true

                binding.textTotalAmount.text = "$repayAmount $unit"
                return
            }
            val couponInfo = JSONObject(data.optString("couponInfo"))
            val amount = couponInfo.optString("amount")
            binding.textCouponDiscount.text = "－$amount $unit"
            binding.couponLayout.isEnabled = true

            binding.textTotalAmount.text = "${repayAmount - amount.toFloat()} $unit"
        }
    }

    /**
     * 设置优惠券列表
     */
    override fun showMullaUserCouponList(couponList: ArrayList<JSONObject>) {
        val useDialog = CouponUseDialog(this,object : CouponUseDialog.IDialogCallback{
            @SuppressLint("SetTextI18n")
            override fun onClick(couponInfo: JSONObject?) {
                presenter.onMullaSetSelectCouponInfo(couponInfo)

                showMullaDufauleUseCouponInfo(couponInfo)
            }
        })
        useDialog.show()
        useDialog.setMullaUserCouponList(couponList)
    }

    /**
     * 设置还款链接
     */
    override fun showMullaLoanPayLink(linkUrl: String) {
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * 进入还款状态查询页面
     */
    override fun showMullaPaymentStatusPage(orderId: String,couponId: String) {
        MullaLoanPaymentStatusAct.start(getContext(),pName,loadProductToken(),orderId,couponId)
    }

    /**
     * 审核中、放款中 根据配置显示公告Dialog
     */
    private fun showMullaLoanNoticeDialog(){
        if (!MullaCustomConfigsHelper.isMullaAuditNotice()){
            return
        }

        val noticeInfo = MullaCustomConfigsHelper.getMullaAuditNoticeInfo() ?: return
        val showNum = noticeInfo.optInt("num",1)
        val completeNum = SharedHelper.getMullaSPInt(SharedHelper.MULLA_SPKEY.MULLA_DIALOG_NOTICE_NUM)
        //本地记录的显示公告次数 >= 配置次数
        if (completeNum >= showNum){
            return
        }

        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_DIALOG_NOTICE_NUM,completeNum+1)
        val noticeDialog = NoticeDialog(this,pName,object : NoticeDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        noticeDialog.show()
        noticeDialog.setTipsTitle(noticeInfo.optString("noticeTitle"))
        noticeDialog.setTips(noticeInfo.optString("noticeText"))
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        pName = loadProductName()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOAN_REPAYMENT_START,pName)
    }

    override fun onStop() {
        super.onStop()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOAN_REPAYMENT_END,pName)
        //已逾期，立即上报
        if (isOverdue){
            FlexiMolaTracker.getInstance(MyApp.app).reportImmediately(null)
        }
    }
}